package com.powerunion.datacollection.dao.impl;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.powerunion.datacollection.common.Constants;
import com.powerunion.datacollection.common.Format;
import com.powerunion.datacollection.common.SystemException;
import com.powerunion.datacollection.dao.DaoException;
import com.powerunion.datacollection.dao.UsersRolesDao;
import com.powerunion.datacollection.model.ApproveWorkItem;
import com.powerunion.datacollection.model.UsersRoles;
import com.powerunion.datacollection.persistence.db.jdbc.operator.QueryOperator;
import com.powerunion.datacollection.persistence.db.jdbc.operator.RsDataSet;
import com.powerunion.datacollection.persistence.db.jdbc.operator.SqlParameter;
import com.powerunion.datacollection.persistence.db.jdbc.operator.SqlType;
import com.powerunion.util.DBUtils;
import com.powerunion.util.log.LogHelper;
import com.powerunion.util.query.jdbc.QueryParameters;

public class UsersRolesDaoImpl extends JdbcBase implements UsersRolesDao{
	// 初始化日志类
	private static final Logger logger = LogHelper.getInstance().getLogger(
			UsersRolesDaoImpl.class);
	
	public boolean save (List users,String roleId) throws DaoException {
		if (logger.isDebugEnabled()) {
			logger.debug(Constants.INTOMETHOD + "save");
		}

		boolean isSuccess = false;
		StringBuffer sqlInsert = new StringBuffer();
		sqlInsert.append("insert into dc_users_roles(id,role_id,user_code,user_type)")
		         .append(" values(?,?,?,?)");
        
        List batchParams = null;

		try {

			batchParams = new ArrayList();
			for(Iterator iter = users.iterator();iter.hasNext();){
				UsersRoles ur = (UsersRoles)iter.next();
				String id = String.valueOf(this.getSeq("dc_users_roles"));
				
				QueryParameters param = new QueryParameters();
				param.addParameter(id, Types.VARCHAR);
				param.addParameter(roleId, Types.VARCHAR);
				param.addParameter(ur.getUserCode(), Types.VARCHAR);
				param.addParameter(ur.getUserType(), Types.VARCHAR);
				
				batchParams.add(param);
			}
			
			this.executeBatch(sqlInsert.toString(), batchParams);
			
			isSuccess = true;
		} catch (Exception e) {
			logger.error("save:" + Constants.SAVE + "UsersRoles" + Constants.FAIL,e);
			return isSuccess;
		}
		if (logger.isDebugEnabled()) {
			logger.debug("save:" + Constants.SAVE + "UsersRoles" + Constants.SUCCESS);
		}

		return isSuccess;

	}

	/**
	 * 根据角色主键删除与该角色有关的用户
	 * @param roleId
	 * @return
	 * @throws DaoException
	 */
	public boolean delete(String roleId) throws DaoException {
		logger.debug(Constants.INTOMETHOD + "delete");
		boolean isSuccess = false;
		String[] codes  = new String[1];
		codes[0] = roleId;
		List batchParams = this.batchParams(codes, Types.VARCHAR);
		if (batchParams != null) {
			logger.error("delete:" + Constants.DELETE + "UsersRoles"
					+ Constants.SUCCESS);
			try {
				this.executeBatch(this.sqlDelete(), batchParams);
				isSuccess = true;
			} catch (SQLException e) {
				logger.error("delete:" + Constants.DELETE + "UsersRoles" + Constants.FAIL,e);
				return isSuccess;
			}
			
			return isSuccess;
		} else {
			return isSuccess;
		}
	}
	
	public List getUsersByRole(String roleId) throws DaoException {
		logger.debug(Constants.INTOMETHOD + "getTabsByRole");
		
		StringBuffer sqlStr = new StringBuffer();
		sqlStr.append("select d.user_code,d.user_type from dc_users_roles d where role_id = ? ")
			  .append("   ");
		
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		List list = null;
		try{
			list = new ArrayList();
			conn = this.getConnection();
			ps = conn.prepareStatement(sqlStr.toString());
			ps.setString(1, roleId);
			rs = ps.executeQuery();
			while(rs.next()) {
				UsersRoles usersRoles = new UsersRoles();
				usersRoles.setUserCode(rs.getString("user_code"));
				usersRoles.setUserType(rs.getString("user_type"));
				String name = this.getNameByCode(usersRoles.getUserCode(), usersRoles.getUserType(), conn);
				
				usersRoles.setUserName(name);
				
				list.add(usersRoles);
			}
		}catch(Exception e) {
			logger.error("getUsersByRole:" + Constants.SEARCH
			+ "UsersRoles" + Constants.FAIL,e);

			throw new DaoException("search db record error!");
		}finally{
			DBUtils.close(rs, ps, conn);
		}
		return list;
	}
	
	private String getNameByCode(String code,String type,Connection conn) throws DaoException {
		//参数为空
		if(StringUtils.isEmpty(code)) {
			String[] args = { "code" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter code NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		//参数为空
		if(StringUtils.isEmpty(type)) {
			String[] args = { "type" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter type NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		
		String sql = "";
		if(type.equals("user")){
			sql = "select f.user_name name from frameuser f where f.user_code=?";
		}else if(type.equals("group")) {
			sql = "select w.grop_name name from workgroup w where w.grop_code=?";
		}else if(type.equals("department")) {
			sql = "select d.dept_name name from framedepartment d where d.dept_code=?";
		}
		
		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());
		query.addParameter(new SqlParameter(SqlType.VARCHAR, code));
		query.setUseOnlyConnectionFlag(true);
		query.setPresentConnection(conn);
		String name = "";
		try{
			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				if(rs.rowCount>0){
					name = rs.getFieldValueAsString("name");
				}

				rs.clearAll();
			}
		}catch(Exception e){
			logger.error("", e);
			throw new DaoException("getNameByCode throws error！");
		}
		return name;
	}


	protected String sqlDelete() {
		StringBuffer sql = new StringBuffer();
		sql.append("delete from dc_users_roles where role_id = ? ");
		return sql.toString();
	}

}
